package com.example.springbootsqlite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author Chen
 * @Date 2021-01-13
 */
public class BinBashUtil {

    private static final Logger LOG = LoggerFactory.getLogger(BinBashUtil.class);

    private BinBashUtil() {
    }

    public static String[] createCommand(String command) {
        String separator = File.separator;
        if ("/".equals(separator)) {
            return new String[]{"/bin/sh", "-c", command};
        } else if ("\\".equals(separator)) {
            return new String[]{"cmd", "/c", command};
        }
        throw new RuntimeException("操作系统不在受支持范围！");
    }

    public static boolean exec(String command, String msg) {
        return exec(createCommand(command), msg, 24 * 60);
    }

    public static boolean exec(String[] c, String msg) {
        return exec(c, msg, 50);
    }

    /**
     * 执行指令
     *
     * @param c       指令
     * @param msg     描述
     * @param timeout 等待执行时间
     * @return true 成功
     */
    public static boolean exec(String[] c, String msg, long timeout) {
        long l = System.currentTimeMillis();
        Process exec = null;
        msg = msg == null ? "" : msg;
        try {
            exec = Runtime.getRuntime().exec(c);
            boolean b = exec.waitFor(timeout, TimeUnit.SECONDS);
            //睡眠，防止错误：process hasn't exited
            Thread.sleep(500);
            //执行成功与结果成功
            return b && 0 == exec.exitValue();
        } catch (InterruptedException i) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(msg + " " + i.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(msg + " " + e.getMessage());
        } finally {
            LOG.info("指令执行耗时：{}ms，设置执行时间：{}s", System.currentTimeMillis() - l, timeout);
            if (exec != null) {
                exec.destroy();
                LOG.info("执行指令结果（0）表示成功：{}, 执行指令：{}", exec.exitValue(), Arrays.toString(c));

                if (0 != exec.exitValue()) {
                    LOG.error("执行指令异常：");
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getErrorStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            LOG.error("    {}", line);
                        }
                    } catch (Exception e) {
                        LOG.error("读取指令执行异常数据失败，e={}", e.getMessage());
                    }
                }
            }
        }
    }

}
